package com.zhl.utils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 获取连接对象的工具类
 */
public class ConnectionUtils {
    //创建本地线程: 装载连接对象
    private  ThreadLocal<Connection> t1 = new ThreadLocal<Connection>();
    //提供Datasource
    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    //获取连接对象
    public  Connection getConnection(){
        try {
            //获取连接对象
            //从本地线程取出连接池对象
            Connection conn = t1.get();
            if(conn == null){
                //从数据源中获取连接对象
                conn = dataSource.getConnection();
                t1.set(conn);
            }
            return conn;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * gei 当前线程进行解绑
     */
    public void remove(){
        t1.remove();//本地线程解绑
    }
}









